import {
  defineStore
} from 'pinia'
import { getUserInfo } from '@/api/login'
import tx from '/static/uniapp/tx.png'
// 创建store,命名规则： useXxxxStore
// 参数1：store的唯一表示
// 参数2：对象，可以提供state actions getters

export const useUserinfoStore = defineStore('Userinfo', {
  // data里中的数据
  state: () => ({
    token: uni.getStorageSync('token') || 'test1',
    googleMapsApiKey: 'AIzaSyDdQIcrkC5BzEmGpX0entO8scSfQYFpvBQ',
    id: '',
    location: {
      lng: '113.556061',
      lat: '22.225548',
      address: '广东省珠海市香洲区粤海东路',
    },
    info: {
      avatar: tx
    },
  }),
  // 计算属性
  getters: {
    getToken: state => state.token,
    getInfo: state => state.info,
  },
  // 相当于 vue中的 methods 既可以写同步代码也可以写异步
  actions: {
    setInfo(info) {
      this.info = info
    },
    async getlocation() {
      return new Promise((resolve,reject)=>{
        uni.getLocation({
          type: 'gcj02',
          success: async (res) => {
            console.log('定位成功', res)
            this.latitude = res.latitude
            this.longitude = res.longitude
            this.location.lng = res.longitude
            this.location.lat = res.latitude
            try {
              this.location.address = await this.getAddress(res.longitude, res.latitude)
            } catch (error) {
              this.location.address = ''
            }
            resolve(this.location);
          },
          fail: (err) => {
            reject('定位失败')
            console.log('定位失败', err)
          },
          complete: (err) => {
          }
        })
      })
    },
    getAddress(longitude, latitude) {
      // 使用谷歌地图Geocoding API进行逆地理编码
      return new Promise((resolve, reject) => {
        uni.request({
          url: `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${this.googleMapsApiKey}`,
          success: (res) => {
            if (res.data && res.data.results && res.data.results.length > 0) {
              resolve(res.data.results[0].formatted_address);
              // this.location.address = res.data.results[0].formatted_address
            } else {
              resolve('');
              // this.location.address = 'Unknown location'
            }
          },
          fail: () => {
            reject('')
            // this.location.address = '地址获取失败'
          }
        })
      })
    },
    async update() {
      let info = await getUserInfo()
      this.info = info
      // if(info){
      //   uni.$uv.route('/pages/Home/home');
      // }
    },
    loginout() {
      uni.showModal({
        title: 'Logout',
        content: 'Are you sure you want to logout?',
        success: (res) => {
          if (res.confirm) {
            // Perform logout action
            this.token = ''
            this.info = {
              avatar: tx
            }
            uni.removeStorage('token')
            uni.showToast({
              title: 'Logged out successfully',
              icon: 'success'
            });
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    },
    setToken(token) {
      if (token) {
        this.token = token
        uni.setStorageSync('token', token)
        this.update()
        uni.$uv.route({
          type: 'tab',
          url: '/pages/Home/home'
        });
      }
    }
  }
})